package com.pur.zsms.weixinpay.weixinPayCaddemo;

import java.net.ConnectException;
import java.util.Map;
import java.util.TreeMap;

import com.pur.zsms.weixinpay.weixinPayCaddemo.dao.QueryDao;
import com.pur.zsms.weixinpay.weixinPayCaddemo.utils.HttpUtil;
import com.pur.zsms.weixinpay.weixinPayCaddemo.utils.XMLUtil;

public class wechatquery {

public static boolean orderquery(QueryDao qd) throws Exception {
		
		int successcode = 0;  //0 success   1 fail
		String appid = qd.getAppid()==null?"":qd.getAppid();
		String sub_appid = qd.getSub_appid()==null?"":qd.getSub_appid();
		String mch_id = qd.getMch_id()==null?"":qd.getMch_id();

		String currTime = Method.getCurrTime(); 
		String time_start = currTime.substring(8, currTime.length());
		String strRandom = Method.buildRandom(4) + "";
		String nonce_str = time_start + strRandom; //随机数生成算法
		
		String sign = "";//签名
		//String sign_type = ""; //默认MD5
		
		String out_trade_no = qd.getOut_trade_no()==null?"":qd.getOut_trade_no();//商户系统内部的订单号，微信订单号、商户订单号二选一必传
		
		String sub_mch_id = qd.getSub_mch_id()==null?"":qd.getSub_mch_id();
		
		String transaction_id = qd.getTransaction_id()==null?"":qd.getTransaction_id();
		
		String QUERY_URL = "https://api.mch.weixin.qq.com/pay/orderquery";
		
		String key = "zzyZzy26262415ZzyzzyzzyZzy262624";
		
		Map<Object, String> map = new TreeMap<Object, String>();
		map.put("appid", appid);
		map.put("sub_appid", sub_appid);
		map.put("mch_id", mch_id);
		map.put("nonce_str", nonce_str);
		//map.put("sign_type", sign_type);
		map.put("out_trade_no", out_trade_no);
		map.put("sub_mch_id", sub_mch_id);
		map.put("transaction_id", transaction_id);
		sign = Method.createSign("UTF-8", map,key);
		map.put("sign", sign);
		
		String requestXML = Method.getRequestXml(map);
		Map map1 = null;
		
		try{
			String resXml = HttpUtil.postData(QUERY_URL, requestXML);
			map1 = XMLUtil.doXMLParse(resXml);
			System.out.println(map1.get("result_code"));
		}catch (ConnectException ce){
			System.out.println("连接超时："+ce.getMessage());
		}catch (Exception e){
			System.out.println("https请求异常："+e.getMessage());
		}
		
		System.out.println("QUERY requestXML::::"+requestXML);
		System.out.println("QUERY resXml::::"+HttpUtil.postData(QUERY_URL, requestXML));
		
		if(map1.get("return_code").equals("SUCCESS")&& map1.get("result_code").equals("SUCCESS")){
			if(map1.get("trade_state").equals("SUCCESS")){
				successcode = 0;
			}else if(map1.get("trade_state").equals("USERPAYING")){
				successcode = 1;
			}
		}else{
			successcode = 1;
		}
		
		if(successcode == 0){
			return true;
		}else{
			return false;
		}
		
	}
}
